import React, { Component } from 'react';
import { connect } from 'dva';
import { Select, Button, Table, DatePicker, Input, Pagination } from 'antd';
import styles from './commList.css';
import { Statistics } from '@/models/connect';
import router from 'umi/router';
import { DEFAULT_PAGE_NUM, DEFAULT_PAGE_SIZE } from '@/const';
import { produce, Draft } from 'immer';
import { QueryListParamsType, deviceKinds } from '@/services/statistics';
import VitalSignsStatistics from './vitalSignsStatistics';
import ByenergyConsumptionStatistics from './byenergyConsumptionStatistics'; //能耗监测
import SportsRecoveryStatistics from './sportsRecoveryStatistics'; //运动康复
import GoodsStatistics from './goodsStatistics'; //物品信息
import EnvironmentStatistics from './environmentStatistics'; // 环境信息
import DrugMedicalStatistics from './drugMedicalStatistics'; //戒毒医疗
import PositionInfoStatistics from './positionInfoStatistics'; //位置信息
import { isMenuVisible } from '@/utils/utils';
import _ from 'lodash';
import locale from 'antd/lib/date-picker/locale/zh_CN';
import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');
// import { ColumnProps } from 'antd/lib/table';
import { Dispatch, AnyAction } from 'redux';
const { Option } = Select;
interface commListPsops {
  drugMedicalList?: Statistics;
  environmentList?: Statistics;
  vitalSignsList?: Statistics;
  sportsRecoveryList?: Statistics;
  byenergyList?: Statistics;
  goodsList?: Statistics;
  positionList?: Statistics;
  loading: boolean;
  dispatch: Dispatch<AnyAction>;
  deviceKinds: Statistics;
}
interface ListState {
  filterQueryParams: QueryListParamsType;
  kinds: any;
  params: any;
  visible: boolean;
}
let api: string = '';
let type: string = '';
class commList extends Component<commListPsops, ListState> {
  // constructor(props: commListPsops) {
  //     super(props);
  state: ListState = {
    filterQueryParams: {
      deviceId: '',
      deviceName: '',
      deviceTypeNo: undefined,
      startTime: 'undefined',
      endTime: 'undefined',
      pageNum: DEFAULT_PAGE_NUM,
      pageSize: 10,
    },
    kinds: [],
    params: {
      deviceTypeNo: this.props.deviceTypeNo,
    },
    visible: true,
  };
  // }
  handleStartDateChange = (date: any, dateString: any) => {
    // 采集开始时间
    this.setState(
      produce((draft: Draft<ListState>): void => {
        draft.filterQueryParams.startTime = dateString;
      }),
    );
  };
  handleEndDateChange = (date: any, dateString: any) => {
    // 采集结束时间
    this.setState(
      produce((draft: Draft<ListState>): void => {
        draft.filterQueryParams.endTime = dateString;
      }),
    );
  };
  async componentWillMount() {
    console.log(type);
    api = this.props.drugApi;
    type = this.props.type;
    const { dispatch } = this.props;
    this.handleFilterQuery();
    const [err, data] = await deviceKinds(this.state.params);
    if (!err) {
      this.setState(
        produce((draft: Draft<ListState>): void => {
          draft.kinds = data;
        }),
      );
    }
  }
  handleInputNoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    //资产编号
    e.persist(); //解决e.target为null
    this.setState(
      produce((draft: Draft<ListState>): void => {
        draft.filterQueryParams.deviceId = e.target.value.replace(/\s+/g, '');
      }),
    );
  };
  handleInputDeviceNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 设备名称
    e.persist();
    this.setState(
      produce((draft: Draft<ListState>): void => {
        draft.filterQueryParams.deviceName = e.target.value.replace(/\s+/g, '');
      }),
    );
  };
  // 资产种类
  handleSelectDeviceTypeChange = (e: string) => {
    this.setState(
      produce((draft: Draft<ListState>): void => {
        draft.filterQueryParams.deviceTypeNo = e;
      }),
    );
  };
  handleFilterQuery = () => {
    // 搜索
    console.log(this.state.filterQueryParams.endTime);
    const { dispatch } = this.props;
    dispatch({ type: api, payload: this.state.filterQueryParams });
  };
  // 页码变化
  handlePageChange: (pageNum: number, pageSize: number | undefined) => void = pageNum => {
    this.setState(
      produce((draft: Draft<ListState>): void => {
        draft.filterQueryParams.pageNum = pageNum;
      }),
      () => this.handleFilterQuery(),
    );
  };
  download: any = () => {
    const { dispatch } = this.props;
    console.log(this.props.expApi);
    dispatch({
      type: this.props.expApi,
      payload: {
        params: this.state.filterQueryParams,
        typeApi: this.props.commListEx,
        name: this.props.name,
      },
    });
  };
  columns: any = [
    {
      title: '资产编号',
      dataIndex: 'deviceId',
      key: 'deviceId',
    },
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      key: 'deviceName',
    },
    {
      title: '资产种类',
      dataIndex: 'deviceTypeName',
      key: 'deviceTypeName',
    },
    {
      title: '信息采集次数',
      dataIndex: 'gatherCount',
      key: 'gatherCount',
      render: (text: any, record: any) => {
        return isMenuVisible(this.props.search) ? (
          <a
            onClick={() => {
              localStorage.setItem('businessField', record.businessField);
              router.push(
                `${this.props.detailsUrl}/?deviceId=${record.deviceId}&deviceName=${record.deviceName}&deviceTypeName=${record.deviceTypeName}&startTime=${this.state.filterQueryParams.startTime}&endTime=${this.state.filterQueryParams.endTime}`,
              );
            }}
          >
            {text}
          </a>
        ) : (
          <a>{text}</a>
        );
      },
    },
    {
      title: '信息报警次数',
      dataIndex: 'deviceAlamCount',
      key: 'deviceAlamCount',
      render: (text: any, record: any) => (
        <a onClick={() => isMenuVisible('iot:deviceAlam:monitorAnalyze') && router.push(`/CallpoliceManage/?deviceId=${record.deviceId}`)}>{text}</a>
      ),
    },
  ];
  //     <a onClick={()=>{
  //       router.push(this.props.detailsUrl);
  //       const { dispatch } = this.props;
  //       dispatch({ type: 'statistics/commListDetail', payload: {deviceId: record.deviceId, deviceNam: record.deviceName, deviceTypeName: record.deviceTypeName}})
  //     }}>{text}</a>
  render() {
    const { drugMedicalList = [] } = this.props;
    const { environmentList = [] } = this.props;
    const { vitalSignsList = [] } = this.props;
    const { byenergyList = [] } = this.props;
    const { goodsList = [] } = this.props;
    const { sportsRecoveryList = [] } = this.props;
    const { positionList = [] } = this.props;
    let list: any = [];
    let liststatistics = null;
    if (type === '0') {
      list = vitalSignsList;
      liststatistics = <VitalSignsStatistics />;
    } else if (type === '1') {
      list = sportsRecoveryList;
      liststatistics = <SportsRecoveryStatistics />;
    } else if (type === '2') {
      list = goodsList;
      liststatistics = <GoodsStatistics />;
    } else if (type === '3') {
      list = drugMedicalList;
      liststatistics = <DrugMedicalStatistics />;
    } else if (type === '4') {
      list = environmentList;
      liststatistics = <EnvironmentStatistics />;
    } else if (type === '5') {
      list = byenergyList;
      liststatistics = <ByenergyConsumptionStatistics />;
    } else if (type === '6') {
      list = positionList;
      liststatistics = <PositionInfoStatistics />;
    }
    console.log(list.total);
    const { kinds } = this.state;
    return this.state.visible ? (
      <div style={{ width: '100%' }} className={styles['commList']}>
        <div
          className={styles['inforAnasy-container-top']}
          style={{ paddingLeft: '0', overflow: 'hidden' }}
        >
          <div className={styles['inforAnasy-container-top-btn']}>
            {isMenuVisible(this.props.menuId) && (
              <Button
                type="link"
                onClick={() => {
                  this.download();
                }}
              >
                <img src={require('@/assets/images/add.png')} alt="" />
                导出EXCEL
              </Button>
            )}
            <Button
              style={{ float: 'right', marginRight: '0' }}
              type="link"
              onClick={() => this.setState({ visible: false })}
            >
              <img src={require('@/assets/images/changeBox.png')} alt="" />
            </Button>
          </div>
          <div style={{ clear: 'both' }}>
            <div
              className={styles['inforAnasy-container-top-input dev-search']}
              style={{ display: 'flex', flexWrap: 'wrap' }}
            >
              <div className={styles['dev-search-select']}>
                <Input
                  onChange={this.handleInputNoChange}
                  placeholder="资产编号"
                  value={this.state.filterQueryParams.deviceId}
                  addonBefore="资产编号"
                  type="number"
                />
              </div>
              <div className={styles['dev-search-select']}>
                <Input
                  onChange={this.handleInputDeviceNameChange}
                  value={this.state.filterQueryParams.deviceName}
                  addonBefore="设备名称"
                  placeholder="请输入设备名称"
                  type="text"
                />
              </div>
              <div className={styles['dev-search-select']}>
                <span className={styles['dev-search-select-title']}>资产种类</span>
                <Select
                  defaultValue=""
                  style={{ width: 200 }}
                  placeholder="请选择资产种类"
                  allowClear={true}
                  value={this.state.filterQueryParams.deviceTypeNo}
                  onChange={this.handleSelectDeviceTypeChange}
                >
                  <Option value="">请选择</Option>
                  {_.map(kinds, (item: any, index: number) => (
                    <Option key={index} value={item.deviceTypeNo}>
                      {item.deviceTypeName}
                    </Option>
                  ))}
                </Select>
              </div>
              <div className={styles['dev-search-select-date']}>
                <span className={styles['dev-search-select-title']}>采集时间</span>
                <DatePicker
                  placeholder="采集开始时间"
                  onChange={this.handleStartDateChange}
                  value={
                    this.state.filterQueryParams.startTime === 'undefined' ||
                    this.state.filterQueryParams.startTime === ''
                      ? undefined
                      : moment(this.state.filterQueryParams.startTime)
                  }
                  // value={this.state.filterQueryParams.startTime}
                  locale={locale}
                />
                <DatePicker
                  className="left_timer_box"
                  placeholder="采集结束时间"
                  style={{ width: '180px' }}
                  value={
                    this.state.filterQueryParams.endTime === 'undefined' ||
                    this.state.filterQueryParams.endTime === ''
                      ? undefined
                      : moment(this.state.filterQueryParams.endTime)
                  }
                  onChange={this.handleEndDateChange}
                  // value={this.state.filterQueryParams.endTime}
                  locale={locale}
                />
              </div>
              <Button type="link" className={styles['search']} onClick={this.handleFilterQuery}>
                搜索
              </Button>
              <Button
                type="link"
                className={styles['search']}
                onClick={() => {
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.filterQueryParams.deviceId = '';
                      draft.filterQueryParams.deviceName = '';
                      draft.filterQueryParams.deviceTypeNo = undefined;
                      draft.filterQueryParams.startTime = 'undefined';
                      draft.filterQueryParams.endTime = 'undefined';
                    }),
                  );
                }}
              >
                重置
              </Button>
            </div>
          </div>
        </div>
        <Table
          scroll={{ y: '500px' }}
          pagination={false}
          columns={this.columns}
          dataSource={list.rows}
          rowKey="deviceId"
        />
        {/* <Pagination onChange={this.handlePageChange} total={list.total * 1} /> */}
        <div className="pagination-box">
          <Pagination
            onChange={this.handlePageChange}
            total={list.total ? list.total * 1 : 0}
            defaultCurrent={this.state.filterQueryParams.pageNum}
            current={this.state.filterQueryParams.pageNum}
          />
          <span className="pagination-title-box">
            第{this.state.filterQueryParams.pageNum}/
            {Math.ceil((list.total ? list.total * 1 : 0) / this.state.filterQueryParams.pageSize)}页
            共{list.total ? list.total * 1 : 0}条
          </span>
        </div>
      </div>
    ) : (
      liststatistics
    );
  }
}
export default connect(({ loading, statistics }: any) => {
  if (type === '0') {
    return {
      loading: loading.effects[api],
      vitalSignsList: statistics.vitalSignsList,
      deviceKinds: statistics.deviceKinds,
    };
  }
  if (type === '1') {
    return {
      loading: loading.effects[api],
      sportsRecoveryList: statistics.sportsRecoveryList,
    };
  }
  if (type === '2') {
    return {
      loading: loading.effects[api],
      goodsList: statistics.goodsList,
      deviceKinds: statistics.deviceKinds,
    };
  }
  if (type === '3') {
    return {
      loading: loading.effects[api],
      drugMedicalList: statistics.drugMedicalList,
      deviceKinds: statistics.deviceKinds,
    };
  }
  if (type === '4') {
    return {
      loading: loading.effects[api],
      environmentList: statistics.environmentList,
      deviceKinds: statistics.deviceKinds,
    };
  }
  if (type === '5') {
    return {
      loading: loading.effects[api],
      byenergyList: statistics.byenergyList,
      deviceKinds: statistics.deviceKinds,
    };
  }
  if (type === '6') {
    return {
      loading: loading.effects[api],
      positionList: statistics.positionList,
      deviceKinds: statistics.deviceKinds,
    };
  }
})(commList);
